package org.example.utils;
import com.codahale.aesgcmsiv.AEAD;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static org.apache.commons.codec.binary.Hex.decodeHex;

/**
 * @Author : Nico
 * @create 2025/4/22 13:43
 */
public class AesGcmSivUtil {
    public static void main(String[] args) {
        try {
//            final AEAD aead = new AEAD(decodeHex("ee8e1ed9ff2540ae8f2ba9f50bc2f27c"));
//
//            final byte[] plaintext = "Hello world".getBytes(StandardCharsets.UTF_8);
//            final byte[] data = "example".getBytes(StandardCharsets.UTF_8);
//
//            // automatically generates a nonce
//            final byte[] ciphertext = aead.seal(plaintext, data);
//
//            // automatically parses the nonce from the ciphertext
//            final Optional<byte[]> result = aead.open(ciphertext, data);
//
//            System.out.println(result.map(String::new));
//

            // 2. 初始化加密器
            AEAD aead = new AEAD(decodeHex("ee8e1ed9ff2540ae8f2ba9f50bc2f27c"));

            // 3. 明文数据
            String plaintext = "Hello, AES-GCM-SIV!";
            byte[] plaintextBytes = plaintext.getBytes(StandardCharsets.UTF_8);

            // 4. 可选关联数据（AAD，用于认证但不加密）
            byte[] aad = "metadata".getBytes(StandardCharsets.UTF_8);

            // 5. 加密（自动生成Nonce）
            byte[] nonce = decodeHex("ee8e5a4e5e47ee8e5a4e5e47");
            byte[] ciphertext = aead.seal(nonce,plaintextBytes, aad);
            System.out.println("密文（Base64）: " + Base64.getEncoder().encodeToString(ciphertext));
//QQrfJr8f761ePTcl7ILaEmYDZ+CTdllac6qcHWJXJ+KXQQ0=

            // 6. 解密
            byte[] decrypted = aead.open(nonce,ciphertext, aad).get();
            System.out.println("解密结果: " + new String(decrypted, StandardCharsets.UTF_8));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
